<template>
    <section class="form-container">
        <div class="form-content">
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
                <el-tabs v-model="tabActiveName" style="min-height: 506px;">

                    <el-tab-pane label="商品信息" name="first">
                        <el-form-item label="商品分类" prop="goodsClassIdLevel" size="mini">
                            <el-cascader
                                v-model="formData.goodsClassIdLevel"
                                :props="cascaderProps"
                                ref="cascaderRef"
                                @change="changeGoodsClass"
                            ></el-cascader>
                        </el-form-item>

                        <el-form-item label="商品名称" prop="goodsName" size="mini">
                            <el-input v-model="formData.goodsName"/>
                        </el-form-item>

                        <el-form-item label="商品描述" prop="goodsDescription" size="mini">
                            <el-input v-model="formData.goodsDescription"/>
                        </el-form-item>

                    </el-tab-pane>
                    <el-tab-pane label="商品规格" name="second">
                        <el-form-item label="商品规格" prop="goodsSpecSel">
                            <el-row v-for="(item,index) in classSpecList" class="spec-value-line-height">
                                <el-col :span="2">{{ item.specName }}：</el-col>
                                <el-col :span="22">
                                    <el-row style="margin-bottom:8px;">
                                        <el-col v-for="s in item.specValueList" :span="4">
                                            <el-checkbox
                                                v-model="s.checked"
                                                :label="s.specValue"
                                                size="large"
                                                @change="createSpecGoods()"
                                            />
                                        </el-col>

                                        <el-link
                                            type="success"
                                            style="line-height: 30px;"
                                            @click="showAddSpecValue(item,-1)"
                                        >+ 添加
                                        </el-link>

                                    </el-row>
                                </el-col>
                            </el-row>
                        </el-form-item>

                        <el-form-item label="商品价格" prop="goodsSpecPrice">
                            <el-row type="flex" class="spec-table-head">
                                <el-col :span="1"></el-col>
                                <el-col :span="5">规格</el-col>
                                <el-col :span="2">原价</el-col>
                                <el-col :span="2">批发价</el-col>
                                <el-col :span="2">库存</el-col>
                                <el-col :span="11">商品名称</el-col>
                                <el-col :span="2">
                                    <el-popconfirm title="确定删除空项吗？" @onConfirm="delEmpty">
                                        <el-link type="success">删除空项</el-link>
                                    </el-popconfirm>
                                </el-col>
                            </el-row>
                            <draggable v-model="pageGoodsSpecList" handle=".el-icon-rank">
                                <el-row type="flex" v-for="(item,index) in pageGoodsSpecList" class="spec-table-body">
                                    <el-col :span="1"><i class="el-icon-rank" style="cursor: move;"/></el-col>
                                    <el-col :span="5">{{ item.specKey }}</el-col>
                                    <el-col :span="2" class="inp-center">
                                        <el-input v-model="item.goodsPrice" :inline="true" size="mini"/>
                                    </el-col>
                                    <el-col :span="2" class="inp-center">
                                        <el-input v-model="item.goodsVipPrice" :inline="true" size="mini"/>
                                    </el-col>
                                    <el-col :span="2" class="inp-center">
                                        <el-input v-model="item.goodsStorage" :inline="true" size="mini"/>
                                    </el-col>
                                    <el-col :span="11">
                                        <el-input v-model="item.goodsName" :inline="true" size="mini"/>
                                    </el-col>
                                    <el-col :span="2">
                                        <el-popconfirm title="确定删除吗？" @onConfirm="deleteSpecGoods(index)">
                                            <el-button slot="reference" size="mini" style="margin:0 0px 10px 10px;">删除
                                            </el-button>
                                        </el-popconfirm>
                                    </el-col>
                                </el-row>
                            </draggable>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="three">
                        <el-form-item
                            v-for="(item,index) in classParamList" :key="index"
                            :label="item.specName"
                            size="mini"
                            label-width="120px"
                        >
                            <el-input type="text" v-model="item.specValue" style="width:200px; margin-right:10px;"></el-input>
                            <el-dropdown @command="changeDropdown" trigger="click">
                                <el-link>选择</el-link>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item v-for="(val,i) in item.specValueList" :command="index+'-'+i" >{{val.specValue}}</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>

                            <el-link
                                type="success"
                                style="line-height: 30px; margin-left:20px;"
                                @click="showAddSpecValue(item,index)"
                            > + 添加
                            </el-link>
                        </el-form-item>
                        <div style="margin-top:30px; font-size: 12px; color:#F00;">*说明：可直接输入，也可选择已有值，或添加值下次可直接选择</div>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="four">
                        <el-row type="flex" class="spec-image-title">
                            <el-col :span="2">默认</el-col>
                            <el-col :span="4">规格</el-col>
                            <el-col :span="4">缩略图(300*300)</el-col>
                            <el-col :span="14">滚动展示图片(800*800)</el-col>
                        </el-row>

                        <el-row type="flex"
                                v-for="(item,index) in pageGoodsSpecList"
                                class="spec-image-list"
                        >
                            <el-col :span="2">
                                <el-radio v-model="defaultSpecKey" :label="item.specKey">{{ '' }}</el-radio>
                            </el-col>
                            <el-col :span="4">{{ item.specKey }}</el-col>
                            <el-col :span="4">
                                <el-upload
                                    class="avatar-uploader"
                                    :action="apiHost + '/file/upload'"
                                    :show-file-list="false"
                                    :on-success="handleSuccess"
                                    :headers="headers"
                                >
                                    <img v-if="item.thumbnail" :src="item.thumbnail" class="avatar"
                                         @click="setCurrentSpec(index)"
                                    />
                                    <i v-else class="el-icon-plus avatar-uploader-icon" @click="setCurrentSpec(index)"/>
                                </el-upload>
                            </el-col>
                            <el-col :span="14">
                                <ul class="el-upload-list el-upload-list--picture-card">
                                    <draggable v-model="item.banner">
                                        <li v-for="(k, index) in item.banner" :key="k.uid"
                                            class="el-upload-list__item is-success animated"
                                        >
                                            <img :src="k.url" alt="" class="el-upload-list__item-thumbnail ">
                                            <i class="el-icon-close"></i>
                                            <span class="el-upload-list__item-actions">
                                            <!-- 预览 -->
                                            <span class="el-upload-list__item-preview"
                                                  @click="handlePictureCardPreview(k)"
                                            >
                                              <i class="el-icon-zoom-in"></i>
                                            </span>
                                                <!-- 删除 -->
                                            <span class="el-upload-list__item-delete" @click="handleRemove(k)">
                                              <i class="el-icon-delete"></i>
                                            </span>
                                          </span>
                                        </li>
                                    </draggable>
                                </ul>

                                <el-upload
                                    :file-list="item.banner"
                                    :action="apiHost + '/file/upload'"
                                    :show-file-list="false"
                                    :on-success="handleSuccessMultiple"
                                    :headers="headers"
                                    list-type="picture-card"
                                    multiple
                                >
                                    <i class="el-icon-plus avatar-uploader-icon" @click="setCurrentSpec(index)"/>
                                </el-upload>
                            </el-col>
                        </el-row>
                    </el-tab-pane>
                    <el-tab-pane label="商品详情" name="five">
                        <editor
                            id="editor_id"
                            height="600px"
                            width="100%"
                            :content="formData.goodsDetail"
                            :load-style-mode="false"
                            :upload-json="apiHost+'/file/upload'"
                            :headers="headers"
                            @on-content-change="onContentChange"
                        />
                    </el-tab-pane>
                </el-tabs>

                <el-form-item>
                    <el-popconfirm :title="'确定保存吗？'" @onConfirm="submitForm()">
                        <el-button slot="reference" type="primary">保存</el-button>
                    </el-popconfirm>
                </el-form-item>
            </el-form>

            <el-dialog :visible.sync="dialogImageVisible">
                <el-image :src="dialogImageUrl" fit="cover">
                    <div slot="error" class="image-slot"
                         style="display: flex;justify-content: center;align-items: center;width: 100%;height: 100%;background: #f5f7fa;color: #909399;font-size: 20px;">
                        <i class="el-icon-picture-outline"></i>
                    </div>
                </el-image>
            </el-dialog>

            <AddOneSpecValue ref="addOneSpecValueRef" @refresh="refreshSpecValue"/>
        </div>
    </section>
</template>

<script>
import {GoodsClassApi} from '@/api/food/goodsClass'
import {SpecApi} from '@/api/food/spec'
import {GoodsApi} from '@/api/food/goods'
import {Common} from '@/utils/common'
import {getToken} from '@/utils/auth'
import AddOneSpecValue from '../spec/AddOneSpecValue.vue'
import editor from '/src/components/Kindeditor/index.vue'
import draggable from 'vuedraggable'
import Vue from 'vue'

export default {
    name: 'FoodGoodsUpdate',
    components: {AddOneSpecValue, editor, draggable},
    data() {
        return {
            formData: {
                id: 0,
                goodsClassId: null,
                goodsName: null,
                goodsDescription: null,

                goodsSpecValueList: [], // 商品参数及规格
                goodsSpecList: [], // 选中规格商品

                goodsDetail: null,
                goodsClassIdLevel: []
            },
            rules: {
                goodsClassIdLevel: [
                    {required: true, message: '请选择商品分类', trigger: 'change', type: 'array'}
                ],
                goodsName: [
                    {required: true, message: '请输入商品名称', trigger: 'blur'},
                    {min: 1, max: 60, message: '长度在 1 到 30 个字符', trigger: 'blur'}
                ]
            },

            classSpecList: [], // 查询出分类下的规格数据
            classParamList: [], // 查询出分类下的商品参数
            classParamAddIndex: -1,

            selectedSpecData:[], //已选规格
            selectedParamData:[], //已选参数

            pageGoodsSpecList: [], // 页面规格处理数据(存储状态用)
            apiHost: process.env.VUE_APP_BASE_API,
            tabActiveName: 'first',
            specIndex: 0,
            dialogImageVisible: false,
            dialogImageUrl: '',

            defaultSpecKey: '',
            headers: {'X-Token': getToken()},
            cascaderProps: {
                lazy: true,
                value: 'id',
                label: 'goodsClassName',
                leaf: 'leaf',
                async lazyLoad(node, resolve) {
                    const {level, data} = node;
                    let parentId = level === 0 ? 0 : data.id
                    GoodsClassApi.getListByParentId(parentId).then((response) => {
                        response.forEach(item => {
                            item.leaf = !item.hasChildren
                        })
                        resolve(response)
                    })
                }
            }
        }
    },
    created() {
        const mainGoodsId = this.$router.currentRoute.query.mainGoodsId
        this.showUpdate(mainGoodsId)
    },
    methods: {
        // 显示组件
        showUpdate(mainGoodsId) {
            this.tabActiveName = 'first'

            if (mainGoodsId > 0) {
                this.$nextTick(() => {
                    this.getGoodsMainDetail(mainGoodsId)
                })
            } else {
                this.formData.id = 0

                if (this.$refs['formRef'] !== undefined) {
                    this.$refs['formRef'].resetFields()
                    this.classSpecList = []
                    this.classParamList = []
                    this.selectedSpecData = []
                    this.selectedParamData = []
                    this.formData.goodsSpecList = []
                    this.pageGoodsSpecList = []
                    this.formData.goodsDetail = ''
                }
            }
        },
        reloadCascader() { //刷新组件，解决回显不生效问题
            let cs = this.$refs["cascaderRef"];
            cs.panel.activePath = [];
            cs.panel.loadCount = 0;
            cs.panel.lazyLoad();
        },
        changeGoodsClass(e) {
            this.formData.goodsClassId = e[e.length - 1]
            this.refreshSpecValue()
        },
        convertSpec(dataList){
            let result = []
            dataList.forEach(function (item, index, arr) {
                let i = -1
                result.forEach(function (cItem, cIndex, cArr) {
                    if (item.specId === cItem.specId) i = cIndex
                })

                if (i > -1) {
                    result[i].specValueList.push({
                        specValue: item.specValue,
                        specValueId: item.specValueId
                    })
                } else {
                    let specObj = {
                        specId: item.specId,
                        specName: item.specName,
                        specType: item.specType,
                        specValueList: [{
                            specValue: item.specValue,
                            specValueId: item.specValueId
                        }]
                    }

                    result.push(specObj)
                }
            })

            return result
        },
        getGoodsMainDetail(id) {
            const that = this
            GoodsApi.getGoodsMainDetail(id).then((response) => {
                that.formData = Common.assign(that.formData, response)

                that.selectedSpecData = that.convertSpec(that.formData.goodsSpecValueList.filter((item) => item.specType === 1));
                that.selectedParamData = that.formData.goodsSpecValueList.filter((item) => item.specType === 2);

                // 添加oss域名
                for (let i = 0; i < response.goodsSpecList.length; i++) {
                    // 转换价格
                    response.goodsSpecList[i].goodsPrice = response.goodsSpecList[i].goodsPrice / 100
                    response.goodsSpecList[i].goodsVipPrice = response.goodsSpecList[i].goodsVipPrice / 100
                }
                that.pageGoodsSpecList = response.goodsSpecList
                let goodsSpecObj = that.pageGoodsSpecList.find(obj => obj.isDefaultCommon)
                if (goodsSpecObj) {
                    that.defaultSpecKey = goodsSpecObj.specKey
                }

                that.getClassSpecList(that.formData.goodsClassId)
                that.reloadCascader()
            })
        },


        refreshSpecValue() {
            const that = this
            if (!that.formData.goodsClassId) return

            that.getClassSpecList(that.formData.goodsClassId);
        },

        // 获取属性并根据已有商品specData设置默认值
        getClassSpecList(goodsClassId) {
            const that = this

            SpecApi.getSpecByGoodsClassId(goodsClassId).then((response) => {
                let classSpecList = response.filter((item) => item.specType === 1);

                //设置默认规格
                const values = []
                that.selectedSpecData.forEach(function (item, index, arr) {
                    item.specValueList.forEach(function (cItem, cIndex, cArr) {
                        values.push(cItem.specValueId)
                    })
                })

                classSpecList.forEach(function (item, index, arr) {
                    item.specValueList.forEach(function (cItem, cIndex, cArr) {
                        cItem['checked'] = values.indexOf(cItem.specValueId) > -1
                    })
                })

                let classParamList = response.filter((item) => item.specType === 2);
                // 设置页面中填写的参数值
                classParamList.forEach(function (item, index, arr) {
                    that.selectedParamData.forEach(function (cItem, cIndex, cArr) {
                        if (item.specId === cItem.specId) {
                            item['specValue'] = cItem['specValue']
                        }
                    })

                    that.classParamList.forEach(function (cItem, cIndex, cArr) {
                        if (item.specId === cItem.specId) {
                            item['specValue'] = cItem['specValue']
                        }
                    })
                })

                // 添加参数后自动选中
                if (that.classParamAddIndex > -1) {
                    let valList = classParamList[that.classParamAddIndex].specValueList
                    let lastObj = valList[valList.length - 1]
                    classParamList[that.classParamAddIndex]['specValue'] = lastObj.specValue
                }

                that.classSpecList = classSpecList
                that.classParamList = classParamList
            })
        },
        //选择参数
        changeDropdown(e){
            let st = e.split('-')
            let k = parseInt(st[0])
            let j = parseInt(st[1])

            let item = this.classParamList[k];
            item['specValue'] = item.specValueList[j].specValue
            Vue.set(this.classParamList, k, item)
        },

        // 循环组合
        generateGroup(arr) {
            // 初始化结果为第一个数组
            var result = arr[0]
            // 从下标1开始遍历二维数组
            for (var i = 1; i < arr.length; i++) {
                // 使用临时遍历替代结果数组长度(这样做是为了避免下面的循环陷入死循环)
                var size = result.length
                // 根据结果数组的长度进行循环次数,这个数组有多少个成员就要和下一个数组进行组合多少次
                for (var j = 0; j < size; j++) {
                    // 遍历要进行组合的数组
                    for (var k = 0; k < arr[i].length; k++) {
                        // 把组合的字符串放入到结果数组最后一个成员中
                        // 这里使用下标0是因为当这个下标0组合完毕之后就没有用了，在下面我们要移除掉这个成员
                        result.push(result[0] + '-' + arr[i][k])
                    }
                    // 当第一个成员组合完毕，删除这第一个成员
                    result.shift()
                }
            }
            // 打印结果
            return result
        },

        deleteSpecGoods(index) {
            this.pageGoodsSpecList.splice(index, 1)
        },

        createSpecGoods() {
            const that = this
            const cacheSpecList = Common.deepClone(that.pageGoodsSpecList)
            that.selectedSpecData = []
            that.pageGoodsSpecList = []

            const tempValue = []
            // 取出已选中内容
            that.classSpecList.forEach(function (item, index, arr) {
                const specArr = []
                const values = []
                item.specValueList.forEach(function (cItem, cIndex, cArr) {
                    if (cItem.checked) {
                        specArr.push(cItem)
                        values.push(cItem.specValue)
                    }
                })

                if (values.length > 0) {
                    const tempObj = Object.assign({}, item)
                    tempObj.specValueList = specArr

                    that.selectedSpecData.push(tempObj)
                    tempValue.push(values)
                }
            })

            if (tempValue.length === 0) return false

            const tempList = this.generateGroup(tempValue)
            tempList.forEach(function (item, index, arr) {
                let goodsSpecObj = cacheSpecList.find(obj => obj.specKey === item)
                if (!goodsSpecObj) {
                    goodsSpecObj = that.formData.goodsSpecList.find(obj => obj.specKey === item)
                }

                const initObj = {
                    'goodsPrice': 0,
                    'goodsVipPrice': 0,
                    'specKey': item,
                    'goodsStorage': 999,
                    'goodsSerial': '',
                    'goodsName': '',
                    'thumbnail': '',
                    'banner': []
                }
                const itemObj = goodsSpecObj === undefined ? initObj : goodsSpecObj

                that.pageGoodsSpecList.push(itemObj)
            })

            that.defaultSpecKey = that.pageGoodsSpecList[0].specKey
        },

        handleSuccess(e) {
            this.pageGoodsSpecList[this.specIndex].thumbnail = e.data
            this.pageGoodsSpecList[this.specIndex].imgHost = ''
        },

        handleSuccessMultiple(response, file, fileList) {
            let that = this

            //多图上传时，此处可解决on-success只进入一次问题
            if (fileList.every(item => item.status === 'success')) {
                fileList.map(item => {
                    if (item.response) {
                        that.pageGoodsSpecList[that.specIndex].banner.push({
                            url: item.response.data
                        })
                    }
                })
            }

            return false
        },

        handleRemove(e) {
            const that = this
            for (let i = 0; i < that.pageGoodsSpecList.length; i++) {
                for (let k = 0; k < that.pageGoodsSpecList[i].banner.length; k++) {
                    if (that.pageGoodsSpecList[i].banner[k].url === e.url) {
                        that.pageGoodsSpecList[i].banner.splice(k, 1)
                    }
                }
            }
        },

        handlePictureCardPreview(e) {
            this.dialogImageVisible = true
            this.dialogImageUrl = e.url
        },

        setCurrentSpec(index) {
            this.specIndex = index
        },

        // 提交表单
        submitForm() {
            const that = this

            that.$refs['formRef'].validate((valid) => {
                if (valid) {
                    const dataForm = Common.deepClone(that.formData)
                    dataForm.goodsSpecValueList=[]
                    dataForm.goodsSpecList = Common.deepClone(that.pageGoodsSpecList)
                    dataForm.goodsSpecList.forEach(item => {
                        item.goodsPrice = item.goodsPrice * 100
                        item.goodsVipPrice = item.goodsVipPrice * 100
                        item.isDefaultCommon = (item.specKey === that.defaultSpecKey)
                    })

                    //组装商品参数
                    that.classParamList.forEach(function (item, index, arr) {
                        let specValueId = null
                        let specValueList = item.specValueList.filter((o) => o.specValue === item.specValue)
                        if(specValueList && specValueList.length > 0){
                            specValueId = specValueList[0].specValueId
                        }

                        const obj = {
                            'specId': item.specId,
                            'specName': item.specName,
                            'specType': item.specType,
                            'specValueId': specValueId,
                            'specValue': item.specValue,
                        }

                        dataForm.goodsSpecValueList.push(obj)
                    })

                    //组装商品规格
                    that.selectedSpecData.forEach(function (item, index, arr) {
                        item.specValueList.forEach(function (cItem, cIndex, cArr) {
                            const obj = {
                                'specId': item.specId,
                                'specName': item.specName,
                                'specType': item.specType,
                                'specValueId': cItem.specValueId,
                                'specValue': cItem.specValue,
                            }
                            dataForm.goodsSpecValueList.push(obj)
                        })
                    })

                    if (dataForm.id > 0) {
                        GoodsApi.updateGoods(dataForm).then(() => {
                            // 调用全局挂载的方法,关闭当前标签页
                            this.$store.dispatch('tagsView/delView', this.$route)
                            // 返回上一步路由，返回上一个标签页
                            this.$router.go(-1)
                        })
                    } else {
                        GoodsApi.addGoods(dataForm).then(() => {
                            // 调用全局挂载的方法,关闭当前标签页
                            this.$store.dispatch('tagsView/delView', this.$route)
                            // 返回上一步路由，返回上一个标签页
                            this.$router.go(-1)
                        })
                    }
                }
            })
        },

        showAddSpecValue(data, index) {
            this.classParamAddIndex = index
            this.$refs['addOneSpecValueRef'].showBox(data)
        },

        delEmpty() {
            this.pageGoodsSpecList = this.pageGoodsSpecList.filter(obj => obj.goodsName !== '')
        },

        onContentChange(val) {
            this.formData.goodsDetail = val
        }
    }
}
</script>

<style scoped>
.el-tabs__content {
    padding: 20px 0;
}

.spec-table-head {
    border: 1px solid #EEE;
}

.spec-table-head .el-col {
    text-align: center;
    font-weight: bold;
}

.spec-table-body {
    border: solid #EEE;
    border-width: 0 1px 1px 1px;
    line-height: 20px;
    align-items: center;
}

.spec-table-body .el-col {
    padding: 5px 5px
}

.spec-table-body .el-input {
    width: 100%;
}

.spec-table-body .el-button {
    margin: 0px !important;
}

::v-deep .spec-table-body .el-input__inner {
    padding: 0 5px;
}

::v-deep .spec-table-body .inp-center .el-input__inner {
    text-align: center
}

::v-deep .spec-value-line-height .el-col {
    line-height: 30px;
}

::v-deep .spec-value-line-height .el-col .el-checkbox {
    height: 30px;
    line-height: 30px;
}

::v-deep .spec-value-line-height .el-checkbox__label {
    white-space: normal;
}

.el-tab-pane {
    padding: 30px 0;
}

::v-deep .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: normal;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px;
}

::v-deep .el-upload-list__item {
    transition: none !important;
}

.spec-image-title {
    border-left: 1px solid #EEE;
    font-size: 14px;
}

.spec-image-title .el-col {
    padding: 10px;
    font-weight: bold;
    border: solid #EEE;
    border-width: 1px 1px 1px 0;
}

.spec-image-list {
    border-left: 1px solid #EEE;
    font-size: 14px;
}

.spec-image-list .el-col {
    padding: 10px;
    border: solid #EEE;
    border-width: 0 1px 1px 0;
}

</style>
